package com.ruoyi.web.controller.common;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.GetObjectRequest;
import com.ruoyi.common.constant.Result;
import com.ruoyi.common.utils.oss.OSSUtil;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;


@CrossOrigin
@RestController
public class FileController {
    /**
     * 文件上传
     *
     * @param file    封装异步提交过来的文件数据的对象
     * @param
     * @return
     * @throws IOException
     */
    @RequestMapping("/fileUpload")
    public Result fileUpload(MultipartFile file) {
// 获取上传的文件的文件名
        String fileName = file.getOriginalFilename();
// 处理文件重名问题: 截取文件扩展名，用UUID替代文件名
        String suffix = fileName.substring(fileName.lastIndexOf("."));

        fileName = UUID.randomUUID().toString() + suffix;

// 当前日期文件夹
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String dateDirPath = sdf.format(new Date());

        // 文件上传的最终路径
        String finalName =   dateDirPath +"/" + fileName;
        String url="";
        try {
            url = OSSUtil.upload(finalName, file.getInputStream());

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        //实现上传功能
        return Result.success( url);



    }

    /**
     * 文件下载
     *
     * @param session
     * @return
     * @throws IOException
     */
    @RequestMapping("/fileDownload")
    public void fileDownload(String filePath, HttpServletResponse response,
                             HttpSession session) throws IOException {
        // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
        String endpoint = "oss-cn-wulanchabu.aliyuncs.com";
        // 填写Bucket名称，例如examplebucket。
        String bucketName = "ffc-sfzy";
        String accessKeyId = "LTAI5tRYX5ro2XRjuPwDDnbF";
        String accessKeySecret = "mWePsOHk6Ims0blMMk8bhOZMi8J5U5";
        // 填写不包含Bucket名称在内的Object完整路径，例如testfolder/exampleobject.txt。
        String objectName = "image/2.jpg";
        // 填写Object下载到本地的完整路径。
        String pathName = "e:\\upload\\55.jpg";

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId,accessKeySecret);

        try {
            // 下载Object到本地文件，并保存到指定的本地路径中。如果指定的本地文件存在会覆盖，不存在则新建。
            // 如果未指定本地路径，则下载后的文件默认保存到示例程序所属项目对应本地路径中。
            ossClient.getObject(new GetObjectRequest(bucketName, objectName), new File(pathName));
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }


}